package com.linian.pushforcampus.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.linian.pushforcampus.domain.PushConfigure;
import com.linian.pushforcampus.domain.UserClass;
import com.linian.pushforcampus.domain.Vip;
import com.linian.pushforcampus.mapper.VipMapper;
import com.linian.pushforcampus.service.VipService;
import com.linian.pushforcampus.util.SymmetricEncryptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/qrcode")
public class QRController {

    @Autowired
    private VipService vipService;
    @Autowired
    private PushConfigure pushConfigure;
    @GetMapping("/create")
    public String showQrCode(@RequestParam("data") String qrCodeData, Model model) throws IOException {
        try {
            String base64Image = generateQRCode(qrCodeData,null);
            // 将Base64编码的图像数据传递到Thymeleaf模板
            model.addAttribute("qrCodeImage", base64Image);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return "qrcodeCreate";
    }
    @GetMapping("/do")
    public String showQrCodeForUser(@RequestParam("data") String qrCodeData, Model model, HttpServletRequest request) throws Exception {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("MicroMessenger")||userAgent.contains("MQQBrowser")) {
            qrCodeData = SymmetricEncryptionUtil.decrypt(qrCodeData, pushConfigure.getSECRET_KEY());
            String cleanedData = qrCodeData.replaceAll("[{}]", "");
            String[] keyValuePairs = cleanedData.split(";");

            String piValue = null;
            String urValue = null;

            for (String pair : keyValuePairs) {
                String[] keyValue = pair.split(":");
                String key = keyValue[0];
                String value = keyValue[1];

                if (key.equals("pi")) {
                    piValue = value;
                } else if (key.equals("ur")) {
                    urValue = value;
                }
            }

            String openid = model.getAttribute("openid").toString();
            if (piValue == null || urValue == null||!openid.substring(openid.length() - 6).equals(urValue)) {
                model.addAttribute("errorMessage", "您没有权限访问该二维码！");
                return handlePermissionError(model);
            }

            List<Vip> ur = vipService.getAllVipsForLike(urValue);
            if (ur.isEmpty()) {
                model.addAttribute("errorMessage", "您没有权限访问该二维码！");
                return handlePermissionError(model);
            }

            String userClassJson = ur.get(0).getUserClass();
            List<UserClass> userClasses = JSON.parseObject(userClassJson, new TypeReference<List<UserClass>>() {
            });

            for (UserClass userClass : userClasses) {
                if (userClass.getPublishId().contains(piValue)) {
                    try {
                        String base64Image = generateQRCode("publishId:" + userClass.getPublishId(),ur.get(0).getUserName());

                        model.addAttribute("qrCodeImage", base64Image);
                        model.addAttribute("activityName", userClass.getActivityName());
                        model.addAttribute("user", ur.get(0).getUserName());
                        model.addAttribute("activityStartTime", userClass.getActivityStartTime());
                        model.addAttribute("activityEndTime", userClass.getActivityEndTime());

                        return "qrcode";
                    } catch (WriterException | IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            model.addAttribute("errorMessage", "您没有权限访问该二维码！");
            return handlePermissionError(model);
        } else {
            model.addAttribute("errorMessage", "请用微信打开该链接！");
            return handlePermissionError(model);
        }
    }

    private String handlePermissionError(Model model) {
        return "error";
    }

    private String generateQRCode(String data,String name) throws WriterException, IOException {
        QRCodeWriter qrWriter = new QRCodeWriter();
        int size = 1000;

        BitMatrix bitMatrix = qrWriter.encode(data, BarcodeFormat.QR_CODE, size, size);
        BufferedImage qrImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                qrImage.setRGB(x, y, bitMatrix.get(x, y) ? 0x000000 : 0xFFFFFF);
            }
        }


        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            if (name!=null){
                // 添加水印
                Graphics2D graphics = qrImage.createGraphics();
//                Font watermarkFont = new Font(Font.SANS_SERIF, Font.ITALIC, 100); // 使用默认字体创建字体对象
                Font watermarkFont = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/fonts/NotoSansSC-Bold.ttf")).deriveFont(Font.PLAIN, 150);
                graphics.setFont(watermarkFont);
                graphics.setColor(new Color(128, 128, 128, 50)); // 设置水印颜色和透明度
                AffineTransform at = new AffineTransform();
                at.rotate(Math.toRadians(0), qrImage.getWidth() / 2, qrImage.getHeight() / 2); // 设置水印旋转角度
                graphics.setTransform(at);
                graphics.drawString("PT", qrImage.getWidth() / 2.5f, qrImage.getHeight() / 2.3f); // 绘制水印文本
                graphics.drawString(name, qrImage.getWidth() / 5f, qrImage.getHeight() / 1.5f); // 绘制水印文本
                watermarkFont = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/fonts/NotoSansSC-Bold.ttf")).deriveFont(Font.PLAIN, 50);
                graphics.setFont(watermarkFont);
                graphics.setColor(Color.RED);
                String watermarkText = "请勿分享";
                int textX = qrImage.getWidth() / 30; // 水印文本的横坐标位置
                int textY = qrImage.getHeight() / 11; // 水印文本的纵坐标位置
                graphics.drawString(watermarkText, textX, textY);
                graphics.dispose();
            }
            ImageIO.write(qrImage, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (FontFormatException e) {
            throw new RuntimeException(e);
        }
    }
}
